/*****************************************************************************
 *
 *                      HUSONG PROPRIETARY INFORMATION
 *
 *          The information contained herein is proprietary to HUSONG
 *           and shall not be reproduced or disclosed in whole or in part
 *                    or used for any design or manufacture
 *              without direct written authorization from HUSONG.
 *
 *            Copyright (c) 2015 by HUSONG.  All rights reserved.
 *
 *****************************************************************************/
package me.send.business.base.openAccount;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.OpenAccount;
import com.taobao.api.domain.OpenaccountLong;
import com.taobao.api.domain.OpenaccountObject;
import com.taobao.api.request.OpenAccountCreateRequest;
import com.taobao.api.request.OpenAccountDeleteRequest;
import com.taobao.api.request.OpenAccountListRequest;
import com.taobao.api.request.OpenAccountUpdateRequest;
import com.taobao.api.response.OpenAccountCreateResponse;
import com.taobao.api.response.OpenAccountDeleteResponse;
import com.taobao.api.response.OpenAccountListResponse;
import com.taobao.api.response.OpenAccountUpdateResponse;

/**
 * 阿里云账号相关操作类
 * 
 * @author maxmin
 *
 * @date 2015年8月3日 上午10:12:22
 */
public class AccountOperate {
	private static final String URL = "http://gw.api.taobao.com/router/rest";
	private static final String USER_APPKEY = "23205578";
	private static final String USER_SECRET = "302f6ae42b0a40f85e75abfe3b58896a";
	private static TaobaoClient USER_CLIENT = new DefaultTaobaoClient(URL,
			USER_APPKEY, USER_SECRET);
	
	private static final String BROKER_APPKEY = "23210327";
	private static final String BROKER_SECRET = "9769cd051ebabd16ff9001e2ef964910";
	private static TaobaoClient BROKER_CLIENT = new DefaultTaobaoClient(URL,
			BROKER_APPKEY, BROKER_SECRET);
	private static final Logger logger = LoggerFactory
			.getLogger("AccountOperate");

	/**
	 * 创建阿里的云账号
	 * 
	 * @return 云账号的id
	 */
	private Long createAccount(TaobaoClient client, String id) {
		OpenAccountCreateRequest req = new OpenAccountCreateRequest();
		OpenAccount param_list = new OpenAccount();
		param_list.setIsvAccountId(id);
		List<OpenAccount> list = new ArrayList<OpenAccount>();
		list.add(param_list);
		req.setParamList(list);
		try {
			OpenAccountCreateResponse response = client.execute(req);
			if (response != null) {
				List<OpenaccountLong> datas = response.getDatas();
				String errCode = response.getErrorCode();
				if (errCode == null || "".equals(errCode)) {
					if (datas != null && datas.size() > 0) {
						OpenaccountLong openaccountLong = datas.get(0);
						if (openaccountLong != null) {
							Long code = openaccountLong.getCode();
							if (ResultCodeCons.SUCCESS_CODE.equals(code)) {
								// 注册成功
								return openaccountLong.getData();
							}
						}
					} else {
						logger.debug("注册云账号失败，datas 为空！");
						System.out.println("注册云账号失败，datas 为空！");
					}
				} else {
					logger.debug("注册云账号失败，errocode:" + errCode);
					System.out.println("注册云账号失败，errocode:" + errCode);
				}
			} else {
				logger.debug("注册云账号失败，response 为空");
				System.out.println("注册云账号失败，response 为空");
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取某个云账号的信息
	 * 
	 * @param id
	 * @return 云账号
	 */
	private OpenAccount accountInfo(TaobaoClient client, Long id) {
		OpenAccountListRequest req = new OpenAccountListRequest();
		req.setOpenAccountIds(id.toString());
		try {
			OpenAccountListResponse response = client.execute(req);
			if (response != null) {
				String errorCode = response.getErrorCode();
				if (errorCode == null || "".equals(errorCode)) {
					List<OpenaccountObject> datas = response.getDatas();
					if (datas != null && datas.size() > 0) {
						OpenaccountObject openaccountObject = datas.get(0);
						if (openaccountObject != null) {
							return openaccountObject.getData();
						}
					}
				}
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 更新云帐号
	 * 
	 * @param id
	 *            云账号id
	 * @param params
	 *            修改的属性
	 * @return 是否修改成功
	 */
	private boolean updateAccount(TaobaoClient client, OpenAccount account) {
		OpenAccountUpdateRequest req = new OpenAccountUpdateRequest();
		List<OpenAccount> list = new ArrayList<OpenAccount>();
		list.add(account);
		req.setParamList(list);
		try {
			OpenAccountUpdateResponse response = client.execute(req);
			if (response != null) {
				String errorCode = response.getErrorCode();
				if (errorCode == null || "".equals(errorCode)) {
					return true;
				}
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 删除云账号
	 * 
	 * @param id
	 *            云账号id
	 * @return 是否删除成功
	 */
	private boolean deleteAccount(TaobaoClient client, Long id) {
		OpenAccountDeleteRequest req = new OpenAccountDeleteRequest();
		req.setOpenAccountIds(id.toString());
		// req.setIsvAccountIds(id.toString());
		try {
			OpenAccountDeleteResponse response = client.execute(req);
			if (response != null) {
				String errorCode = response.getErrorCode();
				if (errorCode == null || "".equals(errorCode)) {
					return true;
				}
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return false;
	}

	private List<OpenaccountObject> getAccounts(TaobaoClient client) {
		OpenAccountListRequest req = new OpenAccountListRequest();
		req.setIsvAccountIds("1,2,3,4,5");
		try {
			OpenAccountListResponse response = client.execute(req);
			if (response != null) {
				return response.getDatas();
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加用户端的云账号
	 * 
	 * @param id
	 * @return
	 */
	public Long createUserAccount(String id) {
		return createAccount(USER_CLIENT, id);
	}

	/**
	 * 添加经纪人端的云账号
	 * 
	 * @param id
	 * @return
	 */
	public Long createBrokerAccount(String id) {
		return createAccount(BROKER_CLIENT, id);
	}

	/**
	 * 用户端云账号信息
	 * 
	 * @param id
	 * @return
	 */
	public OpenAccount userAccountInfo(long id) {
		return accountInfo(USER_CLIENT, id);
	}

	/**
	 * 经纪人端云账号信息
	 * 
	 * @param id
	 * @return
	 */
	public OpenAccount brokerAccountInfo(long id) {
		return accountInfo(BROKER_CLIENT, id);
	}

	/**
	 * 修改用户端的云账号信息
	 * 
	 * @param account
	 * @return
	 */
	public boolean updateUserAccount(OpenAccount account) {
		return updateAccount(USER_CLIENT, account);
	}

	/**
	 * 修改经纪人的云账号信息
	 * 
	 * @param account
	 * @return
	 */
	public boolean updateBrokerAccount(OpenAccount account) {
		return updateAccount(BROKER_CLIENT, account);
	}

	/**
	 * 删除用户端的云账号
	 * 
	 * @param id
	 * @return
	 */
	public boolean deleteUserAccount(Long id) {
		return deleteAccount(USER_CLIENT, id);
	}

	/**
	 * 删除经纪人的云账号
	 * 
	 * @param id
	 * @return
	 */
	public boolean deleteBrokerAccount(Long id) {
		return deleteAccount(BROKER_CLIENT, id);
	}

	/**
	 * 用户端的云账号列表
	 * 
	 * @return
	 */
	public List<OpenaccountObject> getUserAccounts() {
		return getAccounts(USER_CLIENT);
	}

	/**
	 * 经纪人的云账号列表
	 * 
	 * @return
	 */
	public List<OpenaccountObject> getBrokerAccounts() {
		return getAccounts(BROKER_CLIENT);
	}
}
